package com.authine.cloudpivot.web.api.service.impl;

import com.authine.cloudpivot.engine.api.facade.TaskReportFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.type.QueryDisplayType;
import com.authine.cloudpivot.web.api.dao.AtsMapper;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.service.ShopInspectionService;
import com.authine.cloudpivot.web.api.service.StoreService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ShopInspectionServiceImpl implements ShopInspectionService {

    @Autowired
    private DubboConfigService dubboConfigService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private AtsMapper atsMapper;
    @Autowired
    private TaskReportFacade taskReportFacade;

    @Override
    public void createStore(String id, String code) {
        List<String> list = new ArrayList<>();
        list.add("creater");
        list.add("subjectName");
        list.add("projectNo");
        String key = "djxqStore";
        if("DJXQBG".equals(code)){
            key = "djxqbgStore";
        }
        list.add(key);
        //根据id获取店检需求提报的相关信息
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        PageableImpl pageable = new PageableImpl(0, 9999);
        queryModel.setSchemaCode(code);
        queryModel.setQueryCode(code);
        queryModel.setPageable(pageable);
        FilterExpression filterExpression = Q.it("id", FilterExpression.Op.Eq, id);
        queryModel.setFilterExpr(filterExpression);
        BizObjectQueryModel.Options option = new BizObjectQueryModel.Options();
        option.setQueryDisplayType(QueryDisplayType.APPEND);
        option.setCustomDisplayColumns(list);
        queryModel.setOptions(option);
        Page<BizObjectModel> recruitmentDatas = dubboConfigService.getBizObjectFacade().queryBizObjects(queryModel);
        String userId = ((ArrayList<SelectionValue>) recruitmentDatas.getContent().get(0).getData().get("creater")).get(0).getId();
        List<Map<String,Object>> demandDetails = (ArrayList<Map<String,Object>>)recruitmentDatas.getContent().get(0).getData().get(key);
        String subjectName = (String)((HashMap<String,Object>)recruitmentDatas.getContent().get(0).getData().get("subjectName")).get("id");
        String projectNo = (String)recruitmentDatas.getContent().get(0).getData().get("projectNo");
        if(demandDetails != null && demandDetails.size() > 0) {
            //根据项目id查询所有门店
            BizObjectQueryModel queryStoreModel = new BizObjectQueryModel();
            queryStoreModel.setSchemaCode("WHMDXX");
            queryStoreModel.setQueryCode("WHMDXX");
            queryStoreModel.setPageable(pageable);
            FilterExpression storeFilter = Q.it("subjectName", FilterExpression.Op.Eq, subjectName);
            queryStoreModel.setFilterExpr(storeFilter);
            Page<BizObjectModel> storeInfoDatas = dubboConfigService.getBizObjectFacade().queryBizObjects(queryStoreModel);
            List<? extends BizObjectModel> storeModels = storeInfoDatas.getContent();
            Set<String> storeNos = storeModels.stream().map(item -> (String)item.getData().get("customerStoreNum")).collect(Collectors.toSet());
            List<Map<String,Object>> unContainsStores = demandDetails.stream().filter(item -> !storeNos.contains(item.get("storeCode"))).collect(Collectors.toList());
            unContainsStores.forEach(item->{
                //新增该门店信息
                BizObjectModel bizObjectModel = new BizObjectModel();
                bizObjectModel.setSchemaCode("WHMDXX");
                bizObjectModel.setFormCode("WHMDXX");
                bizObjectModel.setSequenceStatus("COMPLETED");
                Map<String, Object> data = bizObjectModel.getData();
                String name = item.get("storeName") != null ? "门店信息-" + item.get("storeName").toString() : null;
                data.put("name", name);
                data.put("customerStoreNum",item.get("storeCode"));
                data.put("customDockingPerson",item.get("storeContacts"));
                data.put("customLinkType",item.get("contactsPhone"));
                data.put("area",item.get("area"));
                data.put("storeShortName", item.get("storeName"));
                data.put("cityLevel",item.get("cityType"));
                data.put("province", item.get("province"));
                data.put("cityName", item.get("city"));
                data.put("storeStatus", "启用");
                data.put("detailArea", item.get("address"));
                data.put("district", item.get("areas"));
                data.put("storeOutlet", item.get("storeChannel"));
                data.put("projectNo",projectNo);
                data.put("subjectName",subjectName);
                data.put("storeNum", getNextStoreNum());
                data.put("djDemand",id);
                data.put("djCount",1);
                dubboConfigService.getBizObjectFacade().saveBizObject(userId, bizObjectModel, false);
            });

            List<Map<String,Object>> containsStores = demandDetails.stream().filter(item -> storeNos.contains((String) item.get("storeCode"))).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(containsStores)) {
                taskReportFacade.updateStoreInfo(id, subjectName, containsStores, "dj");
            }

            if(CollectionUtils.isNotEmpty(demandDetails)){
                taskReportFacade.updateStoreRCSArea(subjectName);
            }
        }
    }

    @Override
    public void updateShopInspection(String id,String updateId) {
        //变更子表
        List<Map<String, Object>> list = atsMapper.getShopInspectionUpdateStores(updateId);
        //删除原先子表
        atsMapper.deleteShopInspectionStores(id);
        //循环更新子表
        List<Map<String, Object>> saveList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Map<String, Object> saveMap = new HashMap<>();
            saveMap.putAll(map);
            saveMap.put("id", UUID.randomUUID().toString().replaceAll("-",""));
            saveMap.put("parentId", id);
            saveList.add(saveMap);
        }
        atsMapper.saveShopInspectionStores(saveList);
    }

    private String getNextStoreNum(){
        String staticStr = "ST";
        String existNum= storeService.getStoreNum();
        if (StringUtils.isEmpty(existNum)) {
            existNum = "ST000001";
        } else {
            existNum= storeService.createStoreNum(staticStr, existNum);
        }
        return existNum;
    }
}



